//////////////////////////////////////////////////////////////////////////////////
// fetchAllUsersServlet
// This Servlet is called to fetch all users in the database
// The Servlet will print out a text response of all usernames in the database 
// separated by commas
///////////////////////////////////////////////////////////////////////////////////



package formServlets;
import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreAttributes;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import javax.servlet.http.HttpServlet;



public class  fetchAllUsersServlet  extends HttpServlet  {

	// doGet forwards whatever requests to doPost, so get and Post do the same thing in this servlet.
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		getServletContext().getRequestDispatcher("SNSP.html").forward(req, resp);
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		// The query is done on UserSignup because all users must have UserSignUp
		// See addUserToDatabase.java for how users are added to the database 
		Query q1 = new Query("UserSignUp");
		
		PreparedQuery pq1 = datastore.prepare(q1);
        String userList=new String();
		for (Entity result : pq1.asIterable()) {
			String user = (String) result.getProperty("Username");
			userList=userList+","+user;
		}
		
		response.getWriter().print(userList);
 
	}
 
}

